<template>
  <div id="login-form">
    <h2>登录</h2>
    <el-form :model="loginMessage" :rules="rules" ref="ruleForm" label-width="auto" class="ruleForm">
      <el-form-item  prop="username">
        <el-input v-model="loginMessage.username" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item  prop="password">
        <el-input type="password" v-model="loginMessage.password" placeholder="请输入密码"/>
      </el-form-item>
    </el-form>
    <button class="login-button" @click="loginClick(loginMessage)">登录</button>
  </div>
</template>

<script>
import {login} from "@/network/userRequest";

export default {
  name: "LoginForm",
  data() {
    return {
      loginMessage: {
        username: "letere",
        password: "123456"
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur"}
        ]
      }
    }
  },
  methods: {
    login(username, password) {
      login(username, password).then(res => {
        if (res.code === 200) {
          this.$store.commit("setToken", res.data);
          this.$message.success("登录成功！")
          this.$router.push("/").catch(err => err);
        } else {
          this.$message.error(res.message, {duration: 3*1000});
        }
      })
    },
    loginClick(loginMessage) {
      this.$refs["ruleForm"].validate(vaild => {
        if (vaild) {
          this.login(loginMessage.username, loginMessage.password);
        }
        else {
          return false;
        }
      })
    }
  }
}
</script>

<style scoped>
  #login-form {
    width: 290px;
    height: 250px;
    padding: 30px;
    text-align: center;
    background-color: white;
    border-radius: 20px;
  }

  #login-form h2 {
    color: #158fc5;
    font-size: 1.5em;
    font-weight: 700;
  }

  #login-form .ruleForm {
    margin-top: 30px;
  }

  #login-form .login-button {
    display: block;
    width: 100%;
    height: 30px;
    font-size: 1.25em;
    color: white;
    font-weight: bolder;
    line-height: 30px;
    border: 1px solid #158fc5;
    border-radius: 15px;
    background-color: #158fc5;
  }

  #login-form .login-button:hover {
    background-color: #1174a0;
    cursor: pointer;
  }
</style>